//
//  AroundViewController.m
//  SXH
//
//  Created by 房 国生 on 15/6/26.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "AroundViewController.h"
#import "AppDelegate.h"
#import "nearTableViewCell.h"
#import "Colours.h"
#import "YYAnimationIndicator.h"
#import "UIImageView+WebCache.h"
#import "WebViewController.h"
#import "CommonService.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "UIView+AutoLayout.h"
#import "AroundHotelViewController.h"
#import "LocationManagement.h"

@interface AroundViewController ()<DPRequestDelegate, MBProgressHUDDelegate>
{
    MBProgressHUD *HUD;
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
}
@property (nonatomic, strong) IBOutlet UIButton *btn1;
@property (nonatomic, strong) IBOutlet UIButton *btn2;
@property (nonatomic, strong) IBOutlet UIButton *btn3;
@property (nonatomic, strong) IBOutlet UILabel *labelTitle;
@property (nonatomic, copy) NSString *strPageNo;

@property (nonatomic, copy) NSString *latitude;
@property (nonatomic, copy) NSString *longitude;
@end

@implementation AroundViewController
@synthesize tableViewBusiness, mutableArrayBusiness, parkEntity;
@synthesize btn1, btn2, btn3, labelTitle,strPageNo,category,latitude,longitude;
@synthesize  enter_type;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    //[btn1 addTarget:self action:@selector(loadArroundData:) forControlEvents:UIControlEventTouchUpInside];
    btn1.tag = 1;
    [btn1.layer setMasksToBounds:YES];
    [btn1.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    
    //[btn2 addTarget:self action:@selector(loadArroundData:) forControlEvents:UIControlEventTouchUpInside];
    btn2.tag = 2;
    [btn2.layer setMasksToBounds:YES];
    [btn2.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    
    //[btn3 addTarget:self action:@selector(loadArroundData:) forControlEvents:UIControlEventTouchUpInside];
    btn3.tag = 3;
    [btn3.layer setMasksToBounds:YES];
    [btn3.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    
    category = 1;
    latitude =[NSString stringWithFormat:@"%f", [LocationManagement sharedInstance].location.coordinate.latitude];
    longitude =[NSString stringWithFormat:@"%f", [LocationManagement sharedInstance].location.coordinate.longitude];

//    if (category == 1) {
//        labelTitle.text = @"酒店";
//    } else if (category == 2) {
//        labelTitle.text = @"美食";
//    } else if (category == 3){
//        labelTitle.text = @"娱乐";
//    }
//
        labelTitle.text = @"周边";

    if (enter_type == 1) {
        labelTitle.text = @"周边";
    } else {
//        btn1.hidden = YES;
//        btn2.hidden = YES;
//        btn3.hidden = YES;
        
//        [self.tableViewBusiness pinToSuperviewEdges:JRTViewPinTopEdge inset:64.0];
//        [self.tableViewBusiness pinToSuperviewEdges:JRTViewPinBottomEdge inset:0.0];
//        [self.tableViewBusiness constrainToSize:CGSizeMake(self.view.bounds.size.width, self.view.frame.size.height)];
    }
    
    page = 1;
    [self addHeader];
    [self addFooter];
    
    //[self loadArroundData:category];
    DebugLog(@"%f, %f", self.view.frame.size.width, self.view.frame.size.height);
    
    self.mutableArrayBusiness = [[NSMutableArray alloc]init];
    //[self loadArroundData:0];
    
    
    UISegmentedControl * controlView = [[UISegmentedControl alloc ] initWithItems:[NSArray arrayWithObjects:@"酒店住宿",@"餐饮美食",@"娱乐休闲", nil]];
    controlView.selectedSegmentIndex = 0;
    controlView.tintColor = [UIColor clearColor];//去掉颜色,现在整个segment都看不见
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                             NSForegroundColorAttributeName:[UIColor colorWithRed:0.439 green:0.769 blue:0.322 alpha:1.00]};
    [controlView setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],
                                               NSForegroundColorAttributeName: [UIColor colorWithRed:0.204 green:0.204 blue:0.204 alpha:1.00f]};
    [controlView setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    [controlView addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    controlView.frame = CGRectMake(0, 62,ScreenWidth,40);
    [self.view addSubview:controlView];
    
    UIView*lineView = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth/3,62 + 5, 1, 40 -10)];
    [lineView setBackgroundColor:[UIColor blackColor]];
    lineView.alpha = 0.1;
    [self.view addSubview:lineView];
    
    UIView*lineView2 = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth/3*2,62 + 5, 1, 40 -10)];
    [lineView2 setBackgroundColor:[UIColor blackColor]];
    lineView2.alpha = 0.1;
    [self.view addSubview:lineView2];

}

- (void)valueChanged:(UISegmentedControl*)seg
{
    [self loadArroundData:seg.selectedSegmentIndex+1 Page:1 RefreshView:nil];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.mutableArrayBusiness count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
     if (NSFoundationVersionNumber>NSFoundationVersionNumber_iOS_7_1) {
     return UITableViewAutomaticDimension;
     }
     */
    return 80;
}

- (void)request:(DPRequest *)request didFailWithError:(NSError *)error {
    [super showLoadingView:NO];
}

- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result {
    //DebugLog(@"%@",[result description]);
    [mutableArrayBusiness removeAllObjects];
    
    NSArray *businesses = [result objectForKey:@"businesses"];
    
    self.mutableArrayBusiness = [NSMutableArray arrayWithArray:businesses];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableViewBusiness reloadData];
    });
    
    [super showLoadingView:NO];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row > [mutableArrayBusiness count]) {
        return nil;
    }
    /*
     static NSString *couponTableViewCellIdentifier=@"AroundTableViewCell";
     [tableView registerNib:[UINib nibWithNibName:@"AroundTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:couponTableViewCellIdentifier];
     AroundTableViewCell *cell = (AroundTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
     
     // Configure the cell...
     NSDictionary *dic = [self.mutableArrayBusiness objectAtIndex:indexPath.row] ;
     NSURL *url = [NSURL URLWithString:[dic objectForKey:@"photo_url"]];
     [cell.imageView setImageWithURL:url];
     
     cell.labelTitle.text = [dic objectForKey:@"name"];
     cell.labelAddress.text = [dic objectForKey:@"address"];
     
     NSNumber *price = [dic objectForKey:@"avg_price"];
     cell.labelPrice.text = [NSString stringWithFormat:@"¥%@",price];
     
     
     cell.labelDistance.text = [NSString stringWithFormat:@"%@米",distance];
     */
    
    [tableView registerClass:[nearTableViewCell class] forCellReuseIdentifier:@"nearTableViewCell"];
    //nearTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearTableViewCell" forIndexPath:indexPath];
    nearTableViewCell *cell  = [[nearTableViewCell alloc] init];
    NSDictionary *dic = [self.mutableArrayBusiness objectAtIndex:indexPath.row];
    NSString * path = [NSString stringWithFormat:@"%@/%@",IMAGE_URL,[dic objectForKey:@"s_photo_url"] ];
    DebugLog(@"%@",path);
    NSURL *url = [NSURL URLWithString:path];
    [cell.myImageView sd_setImageWithURL:url];
    NSNumber *avg_rating = [dic objectForKey:@"avg_rating"];
    cell.myRating.rating = [avg_rating doubleValue];
    
    NSNumber *has_coupon = [dic objectForKey:@"has_coupon"];
    if ([has_coupon intValue]) {
        //[cell.myTagList addTag:@"惠"];
        [cell.myTagList addTag2:@"惠" colour:[UIColor carrotColor]];
    }
    
    NSNumber *has_deal = [dic objectForKey:@"has_deal"];
    if ([has_deal intValue]) {
        //[cell.myTagList addTag:@"团"];
        [cell.myTagList addTag2:@"团" colour:[UIColor cantaloupeColor]];
    }
    
    NSNumber *has_online_reservation = [dic objectForKey:@"has_online_reservation"];
    if ([has_online_reservation intValue]) {
        //[cell.myTagList addTag:@"订"];
        [cell.myTagList addTag2:@"订" colour:[UIColor seafoamColor]];
    }
    
//    NSArray *categories = [dic objectForKey:@"categories"];
//    NSMutableString *tagsString = [[NSMutableString alloc] init];
//    
//    for (NSString *aTag in categories) {
//        [tagsString appendString:aTag];
//        [tagsString appendString:@" "];
//    }

    NSString *tagsString = [dic objectForKey:@"tag"];
    cell.myTags.text = tagsString ;
    
    cell.name.text = [dic objectForKey:@"name"];
    
    NSNumber *distance = [dic objectForKey:@"distance"];
    double theDistance = [distance doubleValue];
    
    cell.distance.text = [NSString stringWithFormat:@"%.2fkm",theDistance/1000.0];
    
        if (theDistance>=1000) {
    
        } else{
            cell.distance.text = [NSString stringWithFormat:@"%@m",distance];
        }
    if ([LocationManagement sharedInstance].location == nil) {
        cell.distance.hidden = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = [self.mutableArrayBusiness objectAtIndex:indexPath.row] ;

    AroundHotelViewController *vc = [[AroundHotelViewController alloc] init];

    vc.parkEntity = parkEntity;
    vc.longitude = longitude;
    vc.longitude = longitude;
    vc.businessid = [dic valueForKeyPath:@"business_id"];
    vc.strTitle = labelTitle.text;
    [self.navigationController pushViewController:vc animated:YES];
}
/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void) goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) loadArroundData:(int)tag Page:(int)pageNo RefreshView:(MJRefreshBaseView *)refreshView{
    
    strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    category = tag;
//    indicator = [[YYAnimationIndicator alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 57)];
//    [indicator setLoadText:@"正在加载..."];
//    [self.view addSubview:indicator];
    
    //[indicator startAnimation];  //开始转动
    

    
    NSString *params = @"";
    if (category == 1) {
        params = @"酒店";
//        params = [NSString stringWithFormat:@"latitude=%@&longitude=%@&category=酒店&sort=2&limit=30",parkEntity.latitude,
//                  parkEntity.longitude];
    } else if (category == 2) {
        params = @"美食";
//        params = [NSString stringWithFormat:@"latitude=%@&longitude=%@&category=休闲娱乐,电影,购物&sort=2&limit=30" ,parkEntity.latitude, parkEntity.longitude];
    } else {
        params = @"休闲娱乐,电影,购物";
//        params = [NSString stringWithFormat:@"latitude=%@&longitude=%@&category=美食&sort=2&limit=30",parkEntity.latitude,
//                  parkEntity.longitude];
    }
    
    //[super showLoadingView:YES];
    //http://api.dianping.com/v1/business/find_businesses?appkey=837230812&sign=80234A7E1B14BADAF47934DA5F18D54089FE831D&category=%E7%BE%8E%E9%A3%9F&city=%E4%B8%8A%E6%B5%B7&latitude=31.18268013000488&longitude=121.42769622802734&sort=1&limit=20&offset_type=1&out_offset_type=1&platform=2
    
//    [[[AppDelegate instance] dpapi] requestWithURL:path paramsString:params delegate:self];
    
    CommonService *service = [[CommonService alloc] init];
    NSString *type = [NSString stringWithFormat:@"%d",tag];
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           type, @"type",
                           strPageNo, @"page",
                           parkEntity.ID,@"parkid",
                           @"20", @"limit",
                           latitude, @"latitude",
                           longitude, @"longitude",nil];
    
    if ([LocationManagement sharedInstance].location == nil) {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                               type, @"type",
                               strPageNo, @"page",
                               parkEntity.ID,@"parkid",
                               @"20", @"limit",
                               @"1", @"latitude",
                               @"1", @"longitude",nil];
        
    }
    
    [service getNetWorkData:param
                       Path:BUSINESSES
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      DebugLog(@"%@", dic);
                      
                      if (pageNo == 1) {
                          [mutableArrayBusiness removeAllObjects];
                      }
                      
                      NSArray *rows = [dic objectForKey:@"rows"];
                      
                      [self.mutableArrayBusiness addObjectsFromArray:rows];
                      
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [self doneWithView:refreshView];
                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];


}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewBusiness;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self loadArroundData:category Page:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewBusiness;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        
        page = 1;
        [self loadArroundData:category Page:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewBusiness reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (IBAction)doSelectData:(id)sender {
    page = 1;
    UIButton *btn = (UIButton *)sender;
    category = btn.tag;
    
    [mutableArrayBusiness removeAllObjects];
    [self loadArroundData:category Page:1 RefreshView:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"AroundViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"AroundViewController"];
}
@end



